﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace WindowsFormsApplication1
{
    public partial class percentDeduction : Form
    {
        private DBConnector connector;
        ListBox parent;
        List<string> checkedItems = new List<string>();
        List<string> checkedNames = new List<string>();
        public percentDeduction(ListBox parent)
        {
            connector = new DBConnector();
            this.parent = parent;
            InitializeComponent();
            initializeContent();
        }

        private void percentDeductionSaveButton_Click(object sender, EventArgs e)
        {
            MiscChargeController miscCharge = new MiscChargeController();
            string query, firstName, lastName;
            checkedItems.Clear();
            foreach (string checkedItem in percentDeductionCheckedListBox.CheckedItems)
            {
                checkedItems.Add(checkedItem);
            }
            if (connector.openConnection())
            {
                query = "UPDATE tipreport set deduction = 0 where periodID = "+miscCharge.getPeriodID();
                try
                {
                    MySqlCommand cmd = new MySqlCommand(query, connector.getConnection());
                    cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Cannot reinitialize employee deductions.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                foreach (string name in checkedItems)
                {
                    firstName = name.Split(',')[1].Trim();
                    lastName = name.Split(',')[0];
                    query = "SELECT * FROM tipreport WHERE employeeCode = (SELECT employeeCode FROM employee WHERE firstName = \'" + firstName + "\' AND lastName = \'" + lastName + "\') and periodID = "+miscCharge.getPeriodID();
                    MySqlDataAdapter dataAdapter = new MySqlDataAdapter(query, connector.getConnection());
                    MySqlCommandBuilder commandBuilder = new MySqlCommandBuilder(dataAdapter);
                    DataTable dataTable = new DataTable();
                    dataAdapter.Fill(dataTable);

                    if (dataTable.Rows.Count > 0)
                    {
                        query = "UPDATE tipreport set deduction = 1 WHERE employeeCode = (SELECT employeeCode FROM employee WHERE firstName = \'" + firstName + "\' AND lastName = \'" + lastName + "\') and periodID = "+miscCharge.getPeriodID();
                        try
                        {
                            MySqlCommand cmd = new MySqlCommand(query, connector.getConnection());
                            cmd.ExecuteNonQuery();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Cannot update deductions for the following employee: "+ name, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }

                    else
                    {
                        query = "INSERT INTO tipreport(employeeCode, periodID, generalTip, charges, absences, subtotal, deduction, totalTip) VALUES((SELECT employeeCode FROM employee WHERE firstName = \'" + firstName + "\' AND lastName = \'" + lastName + "\'), "+miscCharge.getPeriodID()+", 0, 0, 0, 0, 1, 0);";
                        try
                        {
                            MySqlCommand cmd2 = new MySqlCommand(query, connector.getConnection());
                            cmd2.ExecuteNonQuery();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                            MessageBox.Show("Cannot initialize employee tip report", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
            connector.closeConnection();
            this.Close();
        }
        
        public percentDeduction getPercentDeductions()
        {
            return this;
        }

        private void percentDeductionCancelButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        public void initializeContent()
        {
            MiscChargeController miscCharge = new MiscChargeController();
            percentDeductionCheckedListBox.Items.Clear();
            checkedNames.Clear();
            foreach (string strCol in parent.Items)
            {
                percentDeductionCheckedListBox.Items.Add(strCol);
                checkedNames.Add(strCol);
            }
            if (connector.openConnection())
            {
                int check = 0;
                foreach (string name in checkedNames)
                {
                    string firstName = name.Split(',')[1].Trim();
                    string lastName = name.Split(',')[0];
                    string query = "SELECT deduction FROM tipreport WHERE employeeCode = (SELECT employeeCode FROM employee WHERE firstName = \'" + firstName + "\' AND lastName = \'" + lastName + "\') and periodID = " + miscCharge.getPeriodID();
                    MySqlDataAdapter dataAdapter = new MySqlDataAdapter(query, connector.getConnection());
                    MySqlCommandBuilder commandBuilder = new MySqlCommandBuilder(dataAdapter);
                    DataTable dataTable = new DataTable();
                    dataAdapter.Fill(dataTable);
                    if (dataTable.Rows.Count > 0)
                    {
                        check = int.Parse(dataTable.Rows[0][0].ToString());
                        if(check>0)
                            percentDeductionCheckedListBox.SetItemCheckState(percentDeductionCheckedListBox.Items.IndexOf(name), CheckState.Checked);
                        else
                            percentDeductionCheckedListBox.SetItemCheckState(percentDeductionCheckedListBox.Items.IndexOf(name), CheckState.Unchecked);
                    }
                }
                connector.closeConnection();
            }
            else
                MessageBox.Show("Cannot connect to database", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}
